﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';

    var checkWorkload = (rule, value, callback) => {
        if (!value) {
            return callback(new Error("请输入工作量系数"));
        }
        if (value <= 0) {
            return callback(new Error("必须大于0"))
        }
        callback()
    };
    // 实例
    var vm = new Vue({
        el: '#app',
        components: {
            'code-mirror': CodeComponent // 注册 CodeMirror组件
        },
        data: {
            // 角色与权限
            ruleTemplatePermission:false,
            addPermission: false,
            editPermission: false,
            deletePermission: false,
            exportPermission: false,
            importPermission: false,

            language: 'text/x-csharp',   // 指定 CodeMirror显示语言

            // 主页面
            filterName: '',
            templateDialogVisible: false, // 模板对话框显示
            templateDialogTitle: '新建',  // 模板对话框title
            templateActionType: '新建',   // 模板操作类型
            templateLabelWidth:'80px',    // 表单项目标签宽度

            dirDialogVisible:false,       // 目录对话框显示
            dirDilalogTitle:'新建模板',   // 目录对话框title  
            dirActionType: '新建',        // 目录操作类型
            dirLabelWidth: '80px',        // 表单项目标签宽度

            treeData:[],

            directory: {
                id: null,
                isDirectory: true,
                name: null,
                parentId: null,
                parentNmame:null,
                order:0
            },

            // 选中的目录
            selectedDir: {
                id: null,
                isDirectory: true,
                name: null
            },

            ruleTemplate: {
                id: null,
                name: null,
                isDirectory: false,
                Children: [],
                typeName: null,
                script: null,
                parentId: null,
                parentName:null,
                description: null,
                order:0
            },

            defaultProps: {     // 科室和tree-node对象的映射
                label: 'name',
                children: 'children'
            },
        },
        methods: {
            // 自定义表单验证器
            isRequired(rule, value, callback) {
                const vm = this;
                if (vm.ruleTemplate.requireInterval) {
                    if (!vm.ruleTemplate.startTime) {
                        return callback(new Error('请选择开始时间'));
                    }
                    if (!vm.ruleTemplate.endTime) {
                        return callback(new Error('请选择结束时间'));
                    }
                    callback();
                }
            },

            // 打开编辑窗口
            dirShowEdit(data) {
                const vm = this;
                vm.dirActionType = '编辑';
                vm.dirDialogVisible = true;
            },

            // 打开目录新建
            dirShowCreate() {
                const vm = this;
                vm.directory.isDirectory = true;
                vm.directory.name = null;
                vm.directory.order = 0;
                if (vm.selectedDir && vm.selectedDir.id) {
                    vm.directory.parentId = vm.selectedDir.id;
                    vm.directory.parentName = vm.selectedDir.name;
                } else {
                    vm.directory.parentId = null;
                    vm.directory.parentName = "<无>";
                }
                vm.dirDilalogTitle = "新建目录";
                vm.dirActionType = "新建";
                vm.dirDialogVisible = true;
            },

            // 移除目录
            deleteDir(data) {
                const vm = this;
                abp.message.confirm('删除目录将删除所有子项')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/rule-template/delete-directory?id=${data.id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.$refs['template-tree'].remove(data.id);
                                }
                            })
                        }
                    })
            },

            // 目录保存
            dirSave() {
                const vm = this;
                var url = `/api/rule-template/create-directory`;
                if (vm.dirActionType.includes('编辑')) {
                    url = `/api/rule-template/edit-dir-submit`;
                }
                vm.$refs['dirDialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: url,
                            data: JSON.stringify(vm.directory)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.dirDialogVisible = false;
                                vm.loadTreeData();
                                vm.dirResetForm();
                            } else {
                                abp.notify.error(res.error);
                            }
                        });
                    }
                })
            },

            // 编辑
            showEdit(node, data) {
                const vm = this;
                if (data.isDirectory) {
                    vm.dirActionType = "编辑";
                } else {
                    vm.templateActionType = '编辑';
                }
                // 加载节点信息
                vm.loadTemplateDetail(data.id, data.isDirectory)
                    .then(res => {
                        if (data.isDirectory) {// 目录节点
                            vm.dirShowEdit();
                        } else {// 模板节点
                            vm.templateShowEdit();
                        }
                    })
            },

            // 展示新建模板
            templateShowCreate() {
                const vm = this;
                vm.ruleTemplate.isDirectory = false;
                vm.ruleTemplate.order = 0;
                vm.ruleTemplate.typeName = null;
                vm.ruleTemplate.script = '';
                vm.ruleTemplate.description = null
                if (vm.selectedDir.id) {
                    vm.ruleTemplate.parentName = vm.selectedDir.name;
                    vm.ruleTemplate.parentId = vm.selectedDir.id;
                } else {
                    vm.ruleTemplate.parentName = '<无>';
                    vm.ruleTemplate.parentId = null;
                }
                vm.templateDialogTitle = "新建规则";
                vm.templateActionType = "新建";
                vm.templateDialogVisible = true;
            },

            // template 显示编辑对话框
            templateShowEdit(data) {
                const vm = this;
                vm.templateActionType = '编辑';
                vm.templateDialogVisible = true;
            },

            // 保存规则模板
            saveTemplate() {
                const vm = this;
                var url = `/api/rule-template/create-template`;
                if (vm.templateActionType.includes('编辑')) {
                    url =`/api/rule-template/template-edit-submit`
                }
                vm.$refs['templateDialogForm'].validate(valid => {
                    if (valid) {
                        abp.ajax({
                            type: 'post',
                            url: url,
                            data:JSON.stringify(vm.ruleTemplate)
                        }).then(res => {
                            vm.templateDialogVisible = false;
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.loadTreeData();
                            } else {
                                abp.notify.error(res.error);
                            }
                        })
                        vm.templateResetForm();
                    }
                })
            },

            // 删除节点
            remove(node, data) {
                const vm = this;
                if (data.isDirectory) {
                    vm.deleteDir(data);
                } else {
                    vm.deleteTemplate(data)
                }
            },

            // 删除模板
            deleteTemplate(data) {
                var vm = this;
                abp.message.confirm('删除检查项目/目录(包含其所有子级)')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/rule-template/template-delete?id=${data.id}`
                            }).then((res) => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.$refs['template-tree'].remove(data.id);
                                }
                            })
                        }
                    });
            },

            // 加载模板详情
            loadTemplateDetail(id, isDirectory) {
                const vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/rule-template/get-detail?id=${id}`
                    }).then((res) => {
                        if (res.code === 0) {
                            if (!isDirectory) {
                                vm.ruleTemplate = res.data;
                            } else {
                                vm.directory = res.data;
                            }
                            resolve();
                        }
                    })
                });
            },
           

            // 加载"科室列表(Admin角色)" 和 当前科室(无admin角色，有DepartmentUser权限)
            loadTreeData() {
                const vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: "GET",
                        url: `/api/rule-template/load-tree-data?filterName=${vm.filterName}`
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.treeData = res.data;
                            resolve();
                        }
                    });
                });
            },

            // 加载当前权限
            loadPermission() {
                const vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('RuleGroup.RuleTempates')) { // 检查规则模板相关授权
                        vm.ruleTemplatePermission = true;
                        if (abp.auth.isGranted('RuleGroup.RuleTempates.Add')) {// 创建权限
                            vm.addPermission = true;
                        }

                        if (abp.auth.isGranted('RuleGroup.RuleTempates.Eidt')) { // 修改权限
                            vm.editPermission = true;
                        }

                        if (abp.auth.isGranted('RuleGroup.RuleTempates.Delete')) { // 删除权限
                            vm.deletePermission = true;
                        }

                        if (abp.auth.isGranted('RuleGroup.RuleTempates.Export')) { // 导出权限
                            vm.exportPermission = true;
                        }
                    }
                    if (abp.auth.isGranted('RuleGroup.RuleTempates.Import')) { // 导入权限
                        vm.importPermission = true;
                    }
                    resolve();
                });
            },

            // 点击树节点
            nodeClicked(node, obj, aa) {
                const vm = this;
                if (vm.selectedDir.id === node.id) { // 点击的和 selectedDir一致
                    if (node.isDirectory) {
                        vm.$refs["template-tree"].setCurrentKey(null);
                        vm.selectedDir.id = null;
                        vm.selectedDir.isDirectory = null;
                        vm.selectedDir.name = null;
                    } else {
                        vm.$refs["template-tree"].setCurrentKey(null);
                        vm.selectedDir.id = null;
                        vm.selectedDir.isDirectory = null;
                        vm.selectedDir.name = null;
                    }
                }
                else { // 和 selectDir不一致
                    if (node.isDirectory) {
                        vm.$refs["template-tree"].setCurrentKey(node.id);
                        vm.selectedDir.id = node.id;
                        vm.selectedDir.isDirectory = node.isDirectory;
                        vm.selectedDir.name = node.label;
                    } else {
                        vm.$refs["template-tree"].setCurrentKey(null);
                        vm.selectedDir.id = null;
                        vm.selectedDir.isDirectory = null;
                        vm.selectedDir.name = null;
                    }
                }
                
            },

            // 表单重置(目录)
            dirResetForm() {
                const vm = this;
                vm.$refs['dirDialogForm'].resetFields();
                vm.dirDialogVisible = false;
                Object.keys(vm.directory).forEach(key => {
                    vm.directory[key] = null;
                });
                vm.directory.order = 0;
                vm.directory.isDirectory = true;
            },

            // 模板表单
            templateResetForm() {
                const vm = this;
                vm.$refs['templateDialogForm'].resetFields();
                vm.templateDialogVisible = false;
                Object.keys(vm.ruleTemplate).forEach(key => {
                    if (key === 'script') {
                        vm.ruleTemplate[key] = '';
                    } else {
                        vm.ruleTemplate[key] = null;
                    }
                });
                vm.ruleTemplate.isDirectory = false;
                vm.ruleTemplate.order = 0;
            },

            // 导出到JSON文件
            exportToJsonFile() {
                const vm = this;
            },

            // 从JSON文件导入
            importFromJsonFile() {
                const vm =this
            },

            // 初始化
            init() {
                const vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.loadTreeData();
                    });
            }
        },
        created() {
            const vm  = this;
            vm.init();
            vm.dirRules = {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ]
            };
            vm.templatteRules = {
                name: [
                    { required: true, message:'请输入模板明亨',trigger:'blur' }
                ],
                typeName: [
                    { required: true, message:'请输入完整名空间类名' ,trrigger:'blur'}
                ]
            }
        },
        mounted() {
            const vm = this;
        }
    });
});